//
//  LoginView.swift
//  App_Login
//
//  Created by 蒋晨成 on 2021/12/30.
//

import Adaptor
import App_Common
import App_Common_FoundationExtensions
import Center_AppInfo
import RxCocoa
import RxSwift
import SnapKit
import UICore
import UIKit
// swiftlint:disable function_body_length

class LoginView: View {
    override init(frame: CGRect = .zero) {
        super.init(frame: frame)
        setup()
    }

    let openUrl = PublishSubject<String>()
    let disposeBag = DisposeBag()

    @available(*, unavailable)
    required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") }

    private lazy var titleLabel: UILabel = .init()
        .x
        .font(.boldSystemFont(ofSize: 30))
        .textColor(Adaptor.Login.LoginView.titleColor)
        .text(LoginModular.localizedString(key: "Login.Title"))
        .adjustsFontSizeToFitWidth(true)
        .instance

    lazy var mobileTextField: UITextField = .init()
        .x
        .font(.systemFont(ofSize: 18))
        .text(RegisterCenter.mobile ?? "")
        .placeholder(LoginModular.localizedString(key: "Login.Input.Mobile.Placeholder"))
        .keyboardType(.numberPad)
        .textColor(Adaptor.Login.LoginView.titleColor)
        .instance

    private lazy var textFieldEndLine: UIView = .init()
        .x
        .backgroundColor(Adaptor.Login.LoginView.lineColor)
        .instance

    private lazy var registerLabel: UILabel = .init()
        .x
        .textColor(Adaptor.Login.LoginView.textColor)
        .text(LoginModular.localizedString(key: "Login.Label.Mobile.Tips"))
        .font(.systemFont(ofSize: 14))
        .instance

    lazy var sendButton: UIButton = .init(type: .custom)
        .x
        .corners(radius: 26)
        .setBackgroundImage(UIImage(color: Adaptor.Login.LoginView.sendButtonNormalBackgroundColor), for: .normal)
        .setBackgroundImage(UIImage(color: Adaptor.Login.LoginView.sendButtonDisableBackgroundColor), for: .disabled)
        .setTitleColor(Adaptor.Login.LoginView.sendButtonNormalTitleColor, for: .normal)
        .setTitleColor(Adaptor.Login.LoginView.sendButtonDisableTitleColor, for: .disabled)
        .setTitle(LoginModular.localizedString(key: "Login.Button.Mobile.SMS"), for: .normal)
        .enabled(false)
        .instance

    lazy var protcolCheckBox: UIButton = .init(type: .custom)
        .x
        .setImage(LoginModular.image(named: "Login.Checkbox.Selected"), for: .selected)
        .setImage(LoginModular.image(named: "Login.Checkbox.Normal"), for: .normal)
        .instance

    private lazy var protcolLabel: UITextView = {
        let protcolText = LoginModular.localizedString(key: "Login.Text.Agreement")
        guard let range1 = protcolText.range(of: LoginModular.localizedString(key: "Login.Text.Agreement.Protcol")) else { fatalError("text not found") }
        guard let range2 = protcolText.range(of: LoginModular.localizedString(key: "Login.Text.Agreement.Privacy")) else { fatalError("text not found") }
        let adjustFontSize = (Adaptor.Screen.width - 120) / 20.5
        let protcolAttrStr = NSMutableAttributedString(string: protcolText, attributes: [.font: UIFont.systemFont(ofSize: adjustFontSize), .foregroundColor: Adaptor.Login.LoginView.textColor])
        protcolAttrStr.addAttribute(.link, value: "\(AppInfoCenter.agreementURL)", range: protcolText.nsRange(from: range1))
        protcolAttrStr.addAttribute(.link, value: "\(AppInfoCenter.privacyURL)", range: protcolText.nsRange(from: range2))

        let tv = UITextView()
            .x
            .textContainerInset(.zero)
            .isEditable(false)
            .delegate(self)
            .attributedText(protcolAttrStr)
            .backgroundColor(.clear)
            .isScrollEnabled(false)
            .instance

        tv.textContainer.lineFragmentPadding = 0.0
        tv.adjustsFontForContentSizeCategory = true
        return tv
    }()

    private lazy var thirdAuthTitleLabel: UILabel = .init()
        .x
        .textColor(Adaptor.Login.LoginView.textColor)
        .text(LoginModular.localizedString(key: "Login.Label.SignIn.Other"))
        .font(.systemFont(ofSize: 14))
        .instance

    private lazy var leftLine: UIView = .init()
        .x
        .backgroundColor(Adaptor.Login.LoginView.lineColor)
        .instance
    private lazy var rightLine: UIView = .init()
        .x
        .backgroundColor(Adaptor.Login.LoginView.lineColor)
        .instance

    private lazy var loginStackView: UIStackView = .init()
        .x
        .axis(.horizontal)
        .spacing(144.0)
        .instance

    private lazy var appleSignInButton = UIButton(type: .custom)
        .x
        .setImage(LoginModular.image(named: "Login.Apple")?.withTintColor(Adaptor.Login.LoginView.loginButtonTintColor), for: .normal)
        .backgroundColor(Adaptor.Login.LoginView.loginButtonBackgroundColor)
        .corners(radius: 23)
        .instance

    private lazy var wechatSignInButton = UIButton(type: .custom)
        .x
        .setImage(LoginModular.image(named: "Login.WeChat")?.withTintColor(Adaptor.Login.LoginView.loginButtonTintColor), for: .normal)
        .backgroundColor(Adaptor.Login.LoginView.loginButtonBackgroundColor)
        .corners(radius: 23)
        .instance
}

extension LoginView {
    func setup() {
        backgroundColor = Adaptor.Login.background
        setupConstraints()
        setupRx()
    }

    private func setupConstraints() {
        titleLabel.x.add(to: self).snp.makeConstraints {
            $0.leading.equalTo(46)
            $0.trailing.equalTo(-46)
            $0.top.equalTo(safeAreaLayoutGuide.snp.top).offset(40)
        }

        mobileTextField.x.add(to: self).snp.makeConstraints {
            $0.top.equalTo(titleLabel.snp.bottom).offset(80)
            $0.leading.equalTo(46)
            $0.trailing.equalTo(-46)
            $0.height.equalTo(30)
        }

        textFieldEndLine.x.add(to: self).snp.makeConstraints {
            $0.top.equalTo(mobileTextField.snp.bottom)
            $0.leading.equalTo(46)
            $0.trailing.equalTo(-46)
            $0.height.equalTo(1.2)
        }

        registerLabel.x.add(to: self).snp.makeConstraints {
            $0.leading.equalTo(46)
            $0.trailing.equalTo(-46)
            $0.top.equalTo(textFieldEndLine.snp.bottom).offset(12)
        }

        sendButton.x.add(to: self).snp.makeConstraints {
            $0.height.equalTo(52)
            $0.leading.equalTo(46)
            $0.trailing.equalTo(-46)
            $0.top.equalTo(registerLabel.snp.bottom).offset(66)
        }

        protcolCheckBox.x.add(to: self).snp.makeConstraints {
            $0.top.equalTo(sendButton.snp.bottom).offset(10)
            $0.width.height.equalTo(30)
            $0.leading.equalTo(44)
        }

        protcolLabel.x.add(to: self).snp.makeConstraints {
            $0.centerY.equalTo(protcolCheckBox)
            $0.leading.equalTo(protcolCheckBox.snp.trailing)
            $0.height.equalTo(16)
            $0.trailing.equalTo(sendButton)
        }

        loginStackView.x.add(to: self).snp.makeConstraints {
            $0.bottom.equalTo(safeAreaLayoutGuide.snp.bottom).offset(-60)
            $0.centerX.equalToSuperview()
        }

        loginStackView.addArrangedSubview(wechatSignInButton)
        loginStackView.addArrangedSubview(appleSignInButton)

        appleSignInButton.snp.makeConstraints {
            $0.width.height.equalTo(46)
        }
        wechatSignInButton.snp.makeConstraints {
            $0.width.height.equalTo(46)
        }

        thirdAuthTitleLabel.x.add(to: self).snp.makeConstraints {
            $0.centerX.equalToSuperview()
            $0.bottom.equalTo(loginStackView.snp.top).offset(-10)
        }

        leftLine.x.add(to: self).snp.makeConstraints {
            $0.height.equalTo(1.2)
            $0.width.equalTo(50)
            $0.centerY.equalTo(thirdAuthTitleLabel)
            $0.trailing.equalTo(loginStackView)
        }

        rightLine.x.add(to: self).snp.makeConstraints {
            $0.height.equalTo(1.2)
            $0.width.equalTo(50)
            $0.centerY.equalTo(thirdAuthTitleLabel)
            $0.leading.equalTo(loginStackView)
        }
    }

    private func setupRx() {
        let tap = UITapGestureRecognizer()
        addGestureRecognizer(tap)
        tap.rx.event.subscribe(onNext: { [weak self] _ in
            self?.mobileTextField.resignFirstResponder()
        })
        .disposed(by: disposeBag)
    }
}

extension LoginView: UITextViewDelegate {
    func textView(_: UITextView, shouldInteractWith url: URL, in _: NSRange, interaction _: UITextItemInteraction) -> Bool {
        openUrl.onNext(url.absoluteString)
        return false
    }
}
